﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DesignPatterns
{
    /// <summary>
    /// 处理者接口
    /// </summary>
    public interface IHandler
    {
        IHandler SetNext(IHandler handler);
        object Handle(object request);
    }

    /// <summary>
    /// 抽象类
    /// </summary>
    public abstract class AbstractHandler : IHandler
    {

        private IHandler _nextHandler;

        public IHandler SetNext(IHandler handler)
        {
            this._nextHandler = handler;
            return handler;
        }

        /// <summary>
        /// 虚方法，在子类继承中需实现此方法。
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public virtual object Handle(object request)
        {
            if (this._nextHandler != null)
            {
                return this._nextHandler.Handle(request);
            }
            else
            {
                return null;
            }
        }
    }

    /// <summary>
    /// 猴子类
    /// </summary>
    public class MonkeyHandler : AbstractHandler
    {
        public override object Handle(object request)
        {
            if ((request as string) == "猴子")
            {
                return "在猴子类中" + request.ToString();
            }
            else
            {
                return base.Handle(request);                        //父类中的Handle方法        
            }
        }
    }

    /// <summary>
    /// 松鼠类
    /// </summary>
    public class SquirreHandler : AbstractHandler
    {
        public override object Handle(object request)
        {
            if ((request as string) == "松鼠")
            {
                return "在松鼠类中" + request.ToString();
            }
            else
            {
                return base.Handle(request);                        //父类中的Handle方法        
            }
        }
    }

    /// <summary>
    /// 小狗类
    /// </summary>
    public class DogHandler : AbstractHandler
    {
        public override object Handle(object request)
        {
            if ((request as string) == "小狗")
            {
                return "在小狗类中" + request.ToString();
            }
            else
            {
                return base.Handle(request);                        //父类中的Handle方法        
            }
        }
    }

    class ClientHandel
    {
        public static void ClientCode(AbstractHandler handler)
        {
            foreach (var item in new List<string> { "松鼠", "猴子", "人" })
            {
                Console.WriteLine("到底是谁：" + item);
                var result = handler.Handle(item);
                if (result != null)
                {
                    Console.WriteLine("谁：" + result);
                }
                else
                {
                    Console.WriteLine("No Find");
                }
            }
            Console.WriteLine("开始");
        }

    }
}
